<template>
  <div class="custom-container p-5">
    <a-table class="ant-table-striped tablea1" :columns="columns" :loading="tableLoading" :data-source="dataList"
      size="middle" @change="handleTableChange" :rowKey="(record, index) => { return index }"
      :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)" :pagination="false">
      <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
        <div style="padding: 8px">
          <a-input ref="searchInput" :placeholder="`Search ${column.dataIndex}`" :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;background:#fff !important"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" :class="{'custom-placeholder': true}"
            @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)" />
          <a-button type="primary" size="small" style="width: 90px; margin-right: 8px"
            @click="handleSearch(selectedKeys, confirm, column.dataIndex)">
            <template #icon>
              <SearchOutlined style="font-size: 14px; color: #fff" />
            </template>
            搜索
          </a-button>
          <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
            重置
          </a-button>
        </div>
      </template>
      <template #action="{ record }">
        <a-button type="primary" @click="showModal3(record)" v-if="record.desc">编辑</a-button>
        <a-button @click="showModal3(record)" type="primary" v-else>备注</a-button>
      </template>
  
      <template #action1="{ text, record, index}">
        <div style="display: flex;align-items: center;justify-content: center;">
          <span style="margin-right: 3px;">
            {{ record.id }}
          </span>
          <StarOutlined @click="icon_btn(record)" v-if="record.favorite == 0 || record.favorite == null"
            :style="{fontSize:'20px'}" />
          <StarFilled @click="icon_btn(record)" v-else :style="{fontSize:'20px',color:'#3265cb'}" />
        </div>
      </template>
    </a-table>
    <a-pagination style="float: right; margin: 10px" showTotal show-quick-jumper @change="changePage1" size="small"
      @showSizeChange="changePageSize1" :total="tablePageData1.total" v-model:current="tablePageData1.pageIndex"
      show-size-changer :show-total="total => `共 ${total} 条`" />
    <a-modal v-model:visible="visible3" title="备注详情" @ok="handleOk2" centered width="720px" @cancel="save_btn"
      :bodyStyle="{ backgroundColor: '#252525',padding:'30px 30px', color:'#fff',boxSizing:'border-box'}" :footer="null">
      <div style="display: flex;justify-content: space-between;align-items: flex-end;">
        <textarea id="story" name="story" style="color:#000" rows="5" cols="33" v-model="textareaData"></textarea>
        <a-button @click="save_btn">保存</a-button>
      </div>
    </a-modal>
  </div>
</template>
  <script lang="ts">
import { defineComponent, computed, onMounted, onBeforeUnmount, reactive, ref, Ref, toRefs } from 'vue';
import { get_hissignal, set_favorite, set_desc } from '/@/api/biz/index';
import { StarOutlined, StarFilled, SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default defineComponent({
  components: {
    StarOutlined, StarFilled, SearchOutlined
  },
  setup() {
    onMounted(() => {
      get_data()
    })
    const searchInput = ref();
    const sortedInfo = ref({
      columnKey: null,
      order: null
    });

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        sorter: true,
        slots: { customRender: 'action1' },
        // sortOrder: computed(() => sortedInfo.value.columnKey === 'id' && sortedInfo.value.order),
      },
      {
        title: '卫星名',
        dataIndex: 'sat',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          return record.sat.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: '射频通道',
        dataIndex: 'rfin',
        sorter: (a, b) => a.rfin - b.rfin
      },
      {
        title: '中心频率',
        dataIndex: 'cf',
        sorter: (a, b) => a.cf - b.cf
      },
      {
        title: '符号速率',
        align: "center",
        dataIndex: 'rt',
        sorter: (a, b) => a.rt - b.rt
        // slots: {
        //   filterDropdown: 'filterDropdown',
        //   filterIcon: 'filterIcon',
        //   customRender: 'customRender',
        // },
        // onFilter: (value, record) => {
        //   console.log(record, record.value, record.name, 'record')
        //   return record.rt.toString().toLowerCase().includes(value.toLowerCase())
        // },
        // // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        // onFilterDropdownVisibleChange: visible => {
        //   if (visible) {
        //     setTimeout(() => {
        //       console.log(searchInput.value);
        //       searchInput.value.focus();
        //     }, 100);
        //   }
        // },
      },
      {
        title: '信噪比',
        align: "center",
        dataIndex: "snr",
        sorter: (a, b) => a.snr - b.snr
      },
      {
        title: '协议标准',
        align: "center",
        dataIndex: 'std',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          return record.std.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: 'Punture rate',
        align: "center",
        dataIndex: 'puncture_rate',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          return record.puncture_rate.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: 'ModCod',
        align: "center",
        dataIndex: 'modcode',
        sorter: (a, b) => a.modcode - b.modcode

      },
      {
        title: 'Modulation',
        align: "center",
        dataIndex: "modulation",
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          return record.modulation.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: 'pilots',
        align: "center",
        dataIndex: 'pilots',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          return record.pilots.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: '帧长度',
        align: "center",
        dataIndex: 'frame_len',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          return record.frame_len.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: 'spectrum',
        align: "center",
        dataIndex: 'spec',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          return record.spec.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: '滚降系数',
        align: "center",
        dataIndex: 'rdc',
        sorter: (a, b) => {
          // 去除百分比符号，将字符串转换为浮点数  
          const rdcA = parseFloat(a.rdc.replace('%', ''));
          const rdcB = parseFloat(b.rdc.replace('%', ''));
          // 进行数值比较  
          return rdcA - rdcB;
        }
      },
      {
        title: '备注',
        align: "center",
        dataIndex: 'desc',
        slots: { customRender: 'action' },
      },
      {
        title: '首次发现时间',
        align: "center",
        dataIndex: 'first_find_time',
        sorter: (a, b) => new Date(a.first_find_time) - new Date(b.first_find_time)
      },
      {
        title: '最近发现时间',
        align: "center",
        dataIndex: 'last_find_time',
        sorter: (a, b) => new Date(a.last_find_time) - new Date(b.last_find_time)
      },
      // {
      //   title: '发现次数',
      //   align: "center",
      //   dataIndex: 'sampl_times',
      // },
    ]


    const visible3 = ref<boolean>(false); // 控制第三个对话框的显示状态，默认为 false
    // 定义一个响应式字符串变量 textareaData，用于存储文本区域的内容
    let textareaData = ref('')
    // 定义一个响应式字符串变量 descId，用于存储当前记录的描述 ID
    let descId = ref('')
    const showModal3 = (record) => {
      let textarea = document.getElementById('story'); // 获取 ID 为 'story' 的文本区域元素
      visible3.value = true // 显示第三个模态框
      console.log(record, 'record')
      textareaData.value = record.desc // 将记录的描述赋值给 textareaData
      descId.value = record.id // 将记录的 ID 赋值给 descId
      textarea.value = record.desc // 设置文本区域的内容为记录的描述
    }

    const handleOk2 = (e: MouseEvent) => {
      visible3.value = false;
    };


        // 定义一个响应式字符串变量 content，用于存储文本区域的内容
        let content = ref('');
    // 定义一个函数 save_btn，用于保存文本区域的内容并更新记录的描述
    function save_btn() {
      let textarea = document.getElementById('story'); // 获取 ID 为 'story' 的文本区域元素
      content.value = textarea.value; // 将文本区域的内容赋值给 content
      console.log(content.value, 'content-=-=-=-=-=-='); // 打印 content 的值，便于调试

      // 调用 set_resultdesc 函数，传入记录的 ID 和新的描述内容
      set_desc({ sid: descId.value, desc: content.value }).then((res) => {
        // 检查响应数据中的代码是否为 200
        if (res.data.data.result.data.code == 200) {
          message.success('修改成功'); // 显示成功消息
          visible3.value = false; // 关闭第三个模态框
          get_data(); // 调用 sampl 函数，可能是用于刷新数据或执行其他操作
        } else {
          message.error(res.data.data.result.data.message); // 显示失败消息
        }
      });
    }



    // 定义一个函数 icon_btn，用于处理记录的收藏状态
    const icon_btn = (record) => {
      // 检查记录的 favorite 属性是否为 0 或 null
      if (record.favorite == 0 || record.favorite == null) {
        record.favorite = 1; // 如果是，则将其设置为 1（表示收藏）
      } else {
        record.favorite = 0; // 否则，将其设置为 0（表示取消收藏）
      }
      // 调用 set_resultfavorite 函数，传入记录的 id 和新的 favorite 状态
      set_favorite({ sid: record.id, favorite: record.favorite }).then((res) => {
        // 检查响应数据中的代码是否为 200
        if (res.data.data.result.data.code == 200) {
          message.success('操作成功'); // 显示成功消息
          get_data(); // 调用 get_data 函数，可能是用于刷新数据或执行其他操作
        } else {
          message.success(res.data.data.result.data.message); // 显示响应中的消息
        }
      })
    }


    // 自定义筛选菜单START
    const state = reactive({
      searchText: '',
      searchedColumn: '',
    });
    const handleReset = clearFilters => {
      clearFilters();
      state.searchText = '';
    };
    const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      state.searchText = selectedKeys[0];
      state.searchedColumn = dataIndex;
    }
    const dataList = ref([
      // { rt: '张', cf: '1223', sat: 'E190H', rfin: '2', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '李', cf: '3123', sat: 'E190V', rfin: '3', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '陈', cf: '1', sat: 'E190H22', rfin: '4', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '2', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '3', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
      // { rt: '123123', cf: '123123', snr: '123123', std: '123123', pilots: '123123' },
    ])
    const tableLoading = ref(true)
    // 序号排序时通过API获取数据
    const sortOrder = ref()
    const favorites = ref()
    const dobind = (record) => {
      console.log(record, 'record-0=-=-=')
    };
    // 自定义序号排序
    const handleTableChange = (pagination, filters, sorter) => {
      if (sorter.columnKey !== sortedInfo.value.columnKey || sorter.order !== sortedInfo.value.order) {
        sortedInfo.value = sorter;
      }
      if (sorter.columnKey === 'id' && sorter.order) {
        sendSortOrderToAPI(sorter.order);
        favorites.value = 'favorite'

      }
      if (sorter.columnKey === 'id' && !sorter.order) {
        sortOrder.value = null
        favorites.value = null
        get_data()
      }
    }

    const sendSortOrderToAPI = async (order) => {
      sortOrder.value = order == 'ascend' ? 'asc' : 'desc'
      favorites.value = 'favorite'
      get_data(sortOrder.value, favorites.value)
    }
    // 定义一个函数 get_data，用于获取历史信号数据并更新相关状态
    const get_data = () => {
      tableLoading.value = true; // 设置表格加载状态为 true，表示正在加载数据

      // 使用 axios 发起 GET 请求，获取历史信号数据
      get_hissignal({
        epc: tablePageData1.value.pageSize, // 每页显示的记录数
        cpn: tablePageData1.value.pageIndex, // 当前页码
        sort_by: favorites.value,
        sort_order: sortOrder.value
      }).then((res) => {
        // 检查返回的数据长度是否大于 0
        if (res.data.data.result.data.length > 0) {
          tablePageData1.value.total = res.data.data.result.data_count; // 更新总记录数
          dataList.value = res.data.data.result.data; // 将返回的数据赋值给 dataList
          tableLoading.value = false; // 设置表格加载状态为 false，表示数据加载完成
        } else {
          dataList.value = []; // 如果没有数据，清空 dataList
          tableLoading.value = false; // 设置表格加载状态为 false
        }
      });
    };

    // 定义一个响应式对象 tablePageData1，用于存储表格的分页信息
    const tablePageData1 = ref({
      pageIndex: 1, // 当前页码，默认为 1
      pageSize: 10, // 每页显示的记录数，默认为 10
      total: 0 // 总记录数，默认为 0
    });

    // 定义一个函数 changePage1，用于改变表格的页码并重新获取数据
    const changePage1 = (pageIndex) => {
      tablePageData1.value.pageIndex = pageIndex; // 更新当前页码
      get_data(sortOrder.value, favorites.value); // 重新获取数据
    };

    // 定义一个函数 changePageSize1，用于改变表格的每页显示记录数并重新获取数据
    const changePageSize1 = (current, size) => {
      tablePageData1.value.pageIndex = 1; // 重置当前页码为 1
      tablePageData1.value.pageSize = size; // 更新每页显示的记录数
      get_data(sortOrder.value, favorites.value); // 重新获取数据
    };

    return {
      get_data,
      dataList,
      tableLoading,
      columns,
      dobind,
      searchInput,
      sortedInfo,
      handleReset,
      ...toRefs(state),
      handleSearch,
      changePage1,
      changePageSize1,
      tablePageData1,
      icon_btn,
      handleTableChange,
      favorites,
      sendSortOrderToAPI,
      showModal3,
      visible3,
      handleOk2,
      save_btn,
      textareaData
    }
  }
});
  </script>
  
<style lang="less" scoped>
::v-deep .ant-select-selector {
  color: #fff;
}

::v-deep {
  .ant-pagination-total-text {
    color: #fff !important;
  }

  .ant-pagination-options-quick-jumper {
    color: #fff !important;
  }

  .ant-pagination-item-ellipsis {
    color: #fff !important;
  }
}
textarea {
  padding: 10px;
  max-width: 100%;
  line-height: 1.5;
  border-radius: 5px;
  border: 1px solid #ccc;
  box-shadow: 1px 1px 1px #999;
  height: 250px;
  width: 400px;
}
</style>